import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { UploadChangeParam, UploadFile } from 'ng-zorro-antd/upload';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-operamodal',
    templateUrl: './operaModal.component.html',
    styleUrls: ['./weekPlanWorkshop.component.less']
})
export class OperaModalComponent implements OnInit {
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    delData: any = { 'count': 0, 'id': [] };
    upladUrl: any = environment.project + '/file/upload';
    upladDel: any = environment.project + '/file/delete';
    fileList: any = [];

    constructor(
        private msg: NzMessageService,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        switch (this.operaType) {
            case 'add':
                this.getApi(() => {
                    // to do
                });
                break;
            case 'edit':
                let editStatus = false;
                let editCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        editCount += 1;
                        this.objData = item;
                        editStatus = true;
                    }
                }
                if (editStatus && editCount === 1) {
                    if (this.objData.fileUrl) {
                        this.fileList.push({
                            name: this.objData.fileName,
                            url: this.objData.fileUrl
                        });
                    }
                    this.getApi(() => {
                        // 回填数据
                        this.operaData.id = this.objData.id;
                        this.operaData.zc = new Date(this.objData.operTime);
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'del':
                let delStatus = false;
                for (const item of this.responseData) {
                    if (item.checked) {
                        this.objData = item;
                        this.delData.count += 1;
                        this.delData.id.push(item.id)
                        delStatus = true;
                    }
                }
                if (delStatus) {
                    this.getApi(() => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择数据删除');
                }
                break;
        }
    }
    getApi(callback) {
        setTimeout(() => {
            this.Visible = true;
            callback();
        }, 200);
    }
    getWeek(time, type) {
        const date = new Date(time.getTime());
        const YY = date.getFullYear();
        const MM = date.getMonth() + 1;
        const DD = date.getDate();
        const weekDate = new Date(YY, MM - 1, DD);
        const w = weekDate.getDay();
        const d = weekDate.getDate();

        const weekNumber = Math.ceil((d + 6 - w) / 7);

        let newDate: any;
        switch (type) {
            case 'year':
                newDate = YY;
                break;
            case 'month':
                newDate = MM;
                break;
            case 'day':
                newDate = DD;
                break;
            case 'week':
                switch (weekNumber) {
                    case 1: newDate = '一'; break;
                    case 2: newDate = '二'; break;
                    case 3: newDate = '三'; break;
                    case 4: newDate = '四'; break;
                    case 5: newDate = '五'; break;
                }
                break;
        }
        return newDate;
    }
    handleChange(info: UploadChangeParam) {
        switch (info.file.status) {
            case 'done':
                const response = info.file.response;
                if (response) {
                    if (!response.code) {
                        this.fileList.push({
                            name: response.data[0].fileName,
                            url: response.data[0].fileUrl
                        });
                    } else {
                        this.msg.error(response.msg);
                        this.fileList = [];
                    }
                }
                break;
            case 'removed':
                const fileUrl = new FormData();
                fileUrl.append('url', this.fileList[0].url);
                this.http.post(this.upladDel, fileUrl).subscribe((res: any) => {
                    if (!res.code) {
                        this.msg.success('删除成功');
                        this.fileList = [];
                    } else {
                        this.msg.error(res.msg);
                    }
                });
                break;
            case 'error':
                this.msg.error(`${info.file.name} 上传失败`);
                this.fileList = [];
                break;
        }
    }
    Ok() {
        let param: any = {};
        switch (this.operaType) {
            case 'add':
            case 'edit':
                if (!this.operaData.zc || !this.fileList[0] || !this.fileList[0].name || !this.fileList[0].url) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                    return;
                }
                param = {
                    'week': this.getWeek(this.operaData.zc, 'week'),
                    'month': JSON.stringify(this.getWeek(this.operaData.zc, 'month')),
                    'year': JSON.stringify(this.getWeek(this.operaData.zc, 'year')),
                    'fileName': this.fileList[0].name,
                    'fileUrl': this.fileList[0].url
                }
                if (this.operaType === 'edit') {
                    param.id = this.operaData.id;
                }
                break;
            case 'del':
                param = this.delData.id;
                break;
        } 
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                }, 200);
            } else {
                this.msg.error('操作失败');
            }
        });
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}